package com.zqc.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zqc.common.exception.CaptchaException;
import com.zqc.common.lang.Const;
import com.zqc.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码验证功能
 */

@Component
public class CaptchaFilter extends OncePerRequestFilter {
    @Autowired
    public RedisUtil redisUtil;

    @Autowired
    public LoginFailHandler loginFailHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 判断访问路径是否是 /login
        String uri = httpServletRequest.getRequestURI();
        if ("/login".equals(uri) && "POST".equals(httpServletRequest.getMethod())) {

            try {
                validate(httpServletRequest);
            } catch (CaptchaException e) {
                // 将验证失败交给登录失败处理器处理
                loginFailHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
            }

        }
        // 验证通过，放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private void validate(HttpServletRequest httpServletRequest) throws CaptchaException {
        // 获取用户输入的验证码
        String code = httpServletRequest.getParameter("code");
        // 获取token的值来获取redis中存储的系统生成的验证码
        String key = httpServletRequest.getParameter("token");

        // 如果获取的验证码或token为空，直接抛出异常
        if (StringUtils.isBlank(code) || StringUtils.isBlank(key)) {
            throw new CaptchaException("验证码错误!");
        }

        // 用户验证码和redis中的验证码进行匹配
        if (!code.equals(redisUtil.hget(Const.CAPTCHA_KEY, key))) {
            throw new CaptchaException("验证码错误!");
        }

        // 如果匹配正确，将redis中验证码删除
        redisUtil.hdel(Const.CAPTCHA_KEY, key);
    }
}
